package com.ruike.alisurface.ui.setting;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.Serials.outGoods.ShopChUtils;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.GoodsBean;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.ui.adapter.Slot_test_Adapter;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.utils.MYUtiles;
import com.ruike.alisurface.utils.ThreadUtils;
import com.voodoo.lib_frame.view.AutofitTextView;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.ruike.alisurface.utils.ShareKey.IC2_SLOT_NUM;
import static com.ruike.alisurface.utils.ShareKey.Type_Chshopzl;
import static com.ruike.alisurface.utils.ShareKey.Type_Chshopzl_OLD;

/**
 * 货道检测页面
 */
public class SlotTestActivity extends BaseAty {

    @BindView(R.id.goback_imgv)
    ImageView gobackImgv;
    @BindView(R.id.start_et)
    EditText startEt;
    @BindView(R.id.end_et)
    EditText endEt;
    @BindView(R.id.number_et)
    EditText numberEt;
    @BindView(R.id.make_sure_test)
    AutofitTextView makeSureTest;
    @BindView(R.id.Text_all)
    AutofitTextView TextAll;
    @BindView(R.id.slot_cycler)
    RecyclerView slotCycler;

    private int lastTurnSlot = -1;//最后转动货道号

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_slot_test;
    }

    @Override
    protected void initViews() {
        Constant.showShop = true;
        L.i("货道检测页==" + this.getClass().getName());
        initTitleBar(false);
    }

    @Override
    protected void initData() {
        Constant. isMQTTshop = false;
        showProgressDialog("加载数据中，请等待。。。");
        MchApiHttp.getSlots(this); // 获取商品列表数据
        init();
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
        String type = event.getType();
        L.iTag("测试Activity", event.toString());
//        出货倒计时完成
        if (type.equals("出货倒计时完成")) {
            // 失败
            String[] split = event.getMessage().split("@");
            if (split.length > 0) {
                if (lastTurnSlot >= 0) {
                    int slotNumber = Integer.parseInt(split[1]) + 1;
                    for (GoodsBean gbs : dataBeanList) {
                        if (gbs.getIndex() == slotNumber) {
                            gbs.setTurnNumber(-1);
                        }
                    }
                    testAdapter.setData(dataBeanList);
                }
            }
            return;
        }
        if (event.getType().equals(Type_Chshopzl) || event.getType().equals(Type_Chshopzl_OLD)) {
            ShopChUtils.setPutflag(false);
            // 成功
            String message = event.getMessage();
            L.e(message); // 10 0E 02 04 01 00 00 01 13 0B 1D 13 0C 05 1A 9F  第6位-货道号      第8位-电机转动次数
            String[] split = message.split(" ");
            if (split.length >= 8) {
                int slot_num = ShareUtils.getInstance().getInt(IC2_SLOT_NUM, 100);//得到每一个柜子的最大货道
                int slotNumber = ((Integer.parseInt(split[0]) - 10) * slot_num) + Integer.parseInt(split[5], 16) + 1;
                int turnNumber = Integer.parseInt(split[7], 16);
                L.iTag("测试货道: ", "货道号：" + slotNumber + "\t转动次数：" + turnNumber);
                for (GoodsBean gbs : dataBeanList) {
                    if (gbs.getIndex() == slotNumber) {
                        if (gbs.getSlottypeid() == 21003) {//区分电磁锁
                            gbs.setTurnNumber(1);
                            break;
                        }
                        if (turnNumber > 0) {
                            gbs.setTurnNumber(1);
                        } else {
                            gbs.setTurnNumber(-1);
                        }
                    }
                }
                testAdapter.setData(dataBeanList);
                L.iTag("测试货道页=", dataBeanList.get(slotNumber - 1));
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Constant.showShop = false;
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }

    }

    /**
     * 数据初始化
     */
    private void init() {

        gobackImgv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 10);
        slotCycler.setLayoutManager(gridLayoutManager);


        //输完测试的货道以及转动的次数，点击确定按钮
        makeSureTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isTest) {
                    L.i("tjf=测试的货道=", "已经在测试货到了 不可点击了");
                    return;
                }
                try {
                    TestSolt();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        // 一键测试货道按钮
        TextAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isTest) {
                    L.i("tjf=测试的货道=", "已经在测试货到了 不可点击了");
                    return;
                }
                TestAll();
            }
        });

    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    showRightTip("请输入开始货道");
                    break;
                case 1:
                    showRightTip("请输入结束货道");
                    break;
                case 2:
                    showRightTip("请输入要转动的次数");
                    break;
                case 3:
                    isTest = false;
                    removeProgressDialog();
                    showRightTip("所有货道测试完毕");
                    break;
            }
        }
    };

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        JSONObject object = null;
        try {
            object = new JSONObject(requestJsonStr);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String data = object.optString("data");
        if (requestUrl.endsWith("getSlots")) { // 获取商品货道信息
            L.i(requestJsonStr);
            dataBeanList.addAll(GsonUtils.jsonArray2ModelList(data, GoodsBean.class));

            SlotInfor();
            return;
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        L.i(requestUrl + "===error===" + errorMsg);
    }

    List<GoodsBean> dataBeanList = new ArrayList<>();
    Slot_test_Adapter testAdapter;

    /**
     * 获取货道信息和货道类型
     */
    private void SlotInfor() {
        try {
            L.i("货道信息" + dataBeanList.size());
            if (dataBeanList.size() > 0) {
//                testAdapter = new Slot_test_Adapter(this,   dataBeanList);
                testAdapter = new Slot_test_Adapter(this, dataBeanList);
                slotCycler.setAdapter(testAdapter);
                testAdapter.notifyDataSetChanged();
            }

            testAdapter.setOnItemClickListenerr(new Slot_test_Adapter.OnItemClickListenerr() {
                @Override
                public void onGoodsSlotClick(int position) {
                    if (isTest) {
                        L.i("tjf=测试的货道=", "已经在测试货到了 不可点击了");
                        return;
                    }
                    isTest = true;
                    final int index = dataBeanList.get(position).getIndex();
                    showProgressDialog("正在测试第" + index + "货道，请稍后.....", true);
                    List<GoodsBean> dataBeanLists = new ArrayList<>();
                    dataBeanLists.add(dataBeanList.get(position));
                    PutGoods(dataBeanLists);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    boolean isTest = false;


    private void PutGoods(List<GoodsBean> dataBeanList1) {
        L.i("tjf=测试的货道=", " 点击的货道和一键货道");
        try {
            //判断数据是否已经存在
            ThreadUtils.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        for (int i = 0; i < dataBeanList1.size(); i++) {
                            if (!isTest) {
                                Thread.sleep(100);
                                Thread.currentThread().interrupt();
                                ShopChUtils.setPutflag(false);
                                ThreadUtils.removes(this);
                                L.i("tjf==打断当前线程" + Thread.currentThread().isInterrupted());
                                break;
                            }
                            int index = dataBeanList1.get(i).getIndex();
                            lastTurnSlot = index; // 将当前转动货道记录下来，在EventBus回调的时候失败的情况下使用
                            int type = dataBeanList1.get(i).getSlottypeid();
                            L.i("tjf==" + "run: 出货货道：" + index + "出货类型==" + type);
                            ShopChUtils.shopTodo(type, index);
                            if (i == dataBeanList1.size() - 1 && !ShopChUtils.putflag) {
                                handler.sendEmptyMessage(3);
                                L.i("tjf==" + "run: 出货货道：" + index + "出货结束==");
                                return;
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isTest = false;
    }

    int type;

    /**
     * 输入选择测试的货道
     */
    private void TestSolt() {
        try {

            String start = startEt.getText().toString();
            String end = endEt.getText().toString();
            String number = numberEt.getText().toString();
            if (start.equals("")) {
                handler.sendEmptyMessage(0);
                MYUtiles.HideKeyBoard(SlotTestActivity.this);
                return;
            }
            if (end.equals("")) {
                handler.sendEmptyMessage(1);
                MYUtiles.HideKeyBoard(SlotTestActivity.this);
                return;
            }
            if (number.equals("")) {
                handler.sendEmptyMessage(2);
                MYUtiles.HideKeyBoard(SlotTestActivity.this);
                return;
            }
            L.i("tjf=输完测试的货道=", "输完测试的货道以及转动的次数，点击确定按钮 ");
            showProgressDialog("正在测试所选货道，请等待......", true);
            isTest = true;
            ThreadUtils.post(new Runnable() {
                public void run() {
                    int s = Integer.parseInt(start);
                    int e = Integer.parseInt(end) + 1;
                    int n = Integer.parseInt(number);
                    for (int i = s; i < e; i++) {
                        L.d("tjf==" + "run: 出货货道：" + i);
                        for (GoodsBean gdb : dataBeanList) {
                            if (gdb.getIndex() == i) {
                                type = gdb.getSlottypeid();
                                for (int j = 0; j < n; j++) {
                                    if (!isTest) {
                                        try {
                                            Thread.sleep(100);
                                        } catch (InterruptedException e1) {
                                            e1.printStackTrace();
                                        }
                                        Thread.currentThread().interrupt();
                                        ShopChUtils.setPutflag(false);
                                        ThreadUtils.removes(this);
                                        L.i("tjf==打断当前线程" + Thread.currentThread().isInterrupted());

                                        return;
                                    }
                                    int index = gdb.getIndex();
                                    lastTurnSlot = index; // 将当前转动货道记录下来，在EventBus回调的时候失败的情况下使用
                                    ShopChUtils.shopTodo(type, i);
                                }
                            }
                        }
                        if (i == e - 1 && !ShopChUtils.putflag) {
                            L.i("tjf==" + "出货结束==");
                            handler.sendEmptyMessage(3);
                            return;
                        }
                    }
                }
            });
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
        }
    }

    /**
     * 一键测试所有货道
     */
    private void TestAll() {
        try {
            CustomDialog dialog = new CustomDialog.Builder(this)
                    .setTitle("信息提示！！！")
                    .setMessage("确定进行货道测试吗？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            showProgressDialog("正在测试全部货道，请稍后.....", true);
                            try {
                                isTest = true;
                                PutGoods(dataBeanList);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create();
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
